import React, { useReducer, createContext, Context, Dispatch } from 'react';

const ADD_COUNTER = 'ADD_COUNTER'
const SET_ALARMS = 'SET_ALARMS'

/** 同步action */
const addActions = () => ({
    type: ADD_COUNTER
})

/** 异步action */
export const asyncAction = (dispatch: Dispatch<any>) => {
    return {
        asyncAddction() {
            console.log('执行add action 之前')
            setTimeout(() => {
                dispatch(addActions())
            })
        },
        asyncSetAlarms(values: any) {
            dispatch({ type: 'SET_ALARMS', data: values })
        }
    }
}

/** 初始化state */
export const initialReducer = {
    count: 100,
    alarms: []
}

export function reducer(state: typeof initialReducer, action: { type: string, data: any}) {
    switch (action.type) {
        case ADD_COUNTER: 
            return { ...state, count: state.count + 1 }
        case SET_ALARMS:
            return { ...state, alarms: action.data}
        default:
            return state
    }
}

export const ProviderContext: Context<any> = createContext('provider')

export const providerHoc = (reducer: any, initialState: any) => (Com: any) => {
    return () => {
        const [state, dispatch] = useReducer<any>(reducer, initialState)
        const asyncActions: any = asyncAction(dispatch)
        return (
            <ProviderContext.Provider value={{ state, asyncActions }}>
                <Com />
            </ProviderContext.Provider>
        )
    }
}